﻿using IM.Easy.Core.Cache;
using IM.Easy.CoreServices.IServices;
using IM.Easy.SystemServices.IServices;
using SqlSugar;

namespace IM.Easy.Api.HostedService
{
    /// <summary>
    /// 缓存加载器--->加载系统参数到缓存中
    /// </summary>
    public class CacheLoader : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;

        public CacheLoader(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public Task StartAsync(CancellationToken cancellationToken)
        {
            Console.ForegroundColor = ConsoleColor.DarkGreen; // 设置文字颜色为绿色
            Console.BackgroundColor = ConsoleColor.Black; // 设置背景颜色为黑色（可选）
            Console.WriteLine("加载系统默认参数配置");
            using var scope = _serviceProvider.CreateScope();
            var paramsService = scope.ServiceProvider.GetRequiredService<IParamsService>();
            var @params = paramsService.GetAll();

            foreach (var item in @params)
            {
                CacheManager.Set(item.Key, item.Value);
            }
            Console.WriteLine("系统默认参数配置加载完成");


            //配置字典数据
            Console.WriteLine("开始配置字典数据......");
            var dictService = scope.ServiceProvider.GetRequiredService<IDictGlobalService>();
            dictService.SetGlobalData();
            Console.WriteLine("字典数据配置完成......");



            Console.ResetColor(); // 重置颜色，恢复为默认

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }
}
